package cn.edu.lit.jsjxy.CourseExample.chapter4;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import cn.edu.lit.jsjxy.CourseExample.R;

public class SimpleFingerDrawActivity extends Activity implements View
        .OnTouchListener, View.OnClickListener
{
    ImageView imageView;

    Bitmap bitmap;
    Canvas canvas;
    Paint paint;

    float downx, downy, upx, upy;
    Button btnClear;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        Point point = new Point();
        int screenWidth, screenHeight;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_finger_draw);

        imageView = findViewById(R.id.ivFingerDraw);
        btnClear = findViewById(R.id.btnClear);
        btnClear.setOnClickListener(this);
        imageView.setOnTouchListener(this);

        getWindowManager().getDefaultDisplay().getSize(point);


        screenWidth = point.x;
        screenHeight = point.y;

        bitmap = Bitmap.createBitmap(screenWidth * 2 / 3, screenHeight * 2 / 3,
                Bitmap.Config.ARGB_8888);


        canvas = new Canvas(bitmap);

        initCanvas();

        imageView.setImageBitmap(bitmap);

        paint = new Paint();
        paint.setColor(Color.BLUE);


    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent)
    {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downx = motionEvent.getX();
                downy = motionEvent.getY();
                break;

            case MotionEvent.ACTION_MOVE:
                upx = motionEvent.getX();
                upy = motionEvent.getY();
                canvas.drawLine(downx, downy, upx, upy, paint);
                imageView.invalidate();
                downx = upx;
                downy = upy;
                break;

            case MotionEvent.ACTION_UP:
                upx = motionEvent.getX();
                upy = motionEvent.getY();
                canvas.drawLine(downx, downy, upx, upy, paint);
                imageView.invalidate();
                break;

            case MotionEvent.ACTION_CANCEL:
                break;

            default:
                break;

        }
        return true;
    }

    @Override
    public void onClick(View view)
    {
        initCanvas();
    }

    public void initCanvas()
    {
        Bitmap bitmapCy = BitmapFactory.decodeResource(getResources(), R.drawable
                .cy);
        canvas.drawColor(getResources().getColor(R.color.deepskyblue, null));
        canvas.drawBitmap(bitmapCy, 0, 0, null);
        imageView.invalidate();
    }
}
